import svar
import cv2
import numpy as np
import time
import os

def callback_image(image):
  #print(image)
  m= np.array(image)
  m.dtype='uint8'
  print(m.shape,m.dtype.name) # BGRA

  cv2.imshow('video', m)
  cv2.waitKey(10)

rtmv=open("record.rtmv",'wb',buffering=0)
h264=open("record.h264",'wb',buffering=0)

def callback_buf(buf):
  #pass
  m= np.array(buf)
  mem=memoryview(buf)
  print(m.shape,m.dtype.name,m.shape[0],mem) # BGRA
  if m.shape[0] > 128:
    print('h264',m.shape[0])
    h264.write(mem.tobytes())
  rtmv.write(mem.tobytes())#

osdk=svar.load('svar_osdk')

env=osdk.LinuxSetup(True)
vehicle = env.getVehicle()

#vehicle.advancedSensing.startFPVCameraStream(callback_image)
#vehicle.advancedSensing.startMainCameraStream(callback_image)
options={}

options["camera_position"]=osdk.OSDK_CAMERA_POSITION_NO_1
options["playload_index"]=osdk.PAYLOAD_INDEX_0
options["enable_rtmv"]=False
node=osdk.VehicleNode(vehicle,options)

sub_rtmv=osdk.messenger.subscribe("rtmv",0,callback_buf)

#node.newPhotoNotify()
downloaded={}
savefolder='.'
is_first=True

while(True):
  vehicle.cameraManager.setModeSync(osdk.PAYLOAD_INDEX_0,osdk.MEDIA_DOWNLOAD,2)
  vehicle.cameraManager.obtainDownloadRightSync(osdk.PAYLOAD_INDEX_0,True,2)

  file_list=vehicle.cameraManager.reqFileList(osdk.PAYLOAD_INDEX_0)

  media=file_list.media
  print("there are ",len(media),"files")

  for m in media:
    if m.fileName.find('WIDE') < 0:
      continue
    if m.fileName.find('198000000') > 0:
      print("abort",m)
      continue
    file_path=os.path.join(savefolder,m.fileName)

    if downloaded.get(m.fileIndex) != None:
      print("abort",m.fileName)
      continue

    if os.path.exists(file_path):
      continue
    if is_first:
      downloaded[m.fileIndex]=m
      continue
    print("reqesting file",file_path,"id",m.fileIndex)
    ret=vehicle.cameraManager.reqFileData(osdk.PAYLOAD_INDEX_0,m.fileIndex,file_path)
    print("reqest finished with code:",ret)
    if ret !=0:
      osdk.ErrorCode.printErrorCodeMsg(ret)
      break
  
  if len(media) > 0:
    is_first=False

  time.sleep(3)

time.sleep(100)

